package com.gitee.feizns.itrip.personal.auth.service.impl;

import com.gitee.feizns.itrip.personal.auth.service.exception.AuthException;
import com.gitee.feizns.itrip.personal.auth.service.LoginService;
import com.gitee.feizns.itrip.personal.beans.dto.Token;
import com.gitee.feizns.itrip.personal.beans.pojo.User;
import com.gitee.feizns.itrip.personal.mapper.UserMapper;
import com.gitee.feizns.itrip.personal.utils.service.AbstractService;
import com.gitee.feizns.itrip.personal.utils.service.TokenService;
import com.gitee.feizns.itrip.personal.utils.service.exception.TokenException;
import com.gitee.feizns.itrip.personal.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.gitee.feizns.itrip.personal.utils.service.exception.TokenException.TOKEN_INVALID;

/**
 * token规则： => MD5(UUID()) + '^-^' + userId
 * @author feizns
 * @since 2018/12/29 0029
 */
@Service
public class LoginServiceImpl extends AbstractService<User, UserMapper> implements LoginService {

    @Autowired
    private TokenService tokenService;

    @Override
    public Token login(String userCode, String password) {
        User user = new User(userCode, Utils.getMD5(password));
        user.setActivated(UserMapper.ACTIVATED);
        user = baseMapper.selectOne(user);
        if( user == null )
            throw new AuthException(AuthException.AUTH_VALIDATE, "用户名或密码不正确.");

        return tokenService.generatorToken(user);
    }

    @Override
    public Token reToken(String token) {
        Token verification = tokenService.verification(token);
        if( verification == null )
            throw new TokenException(TOKEN_INVALID, "令牌无效.");

        if( Math.abs(System.currentTimeMillis() - verification.getGenTime()) < DEFAULT_TOKEN_ALLOW_REPLACE_TIME)   //token保护期
            return verification;

        tokenService.deleteToken(verification);
        return tokenService.generatorToken(tokenService.getUser(verification));
    }

    @Override
    public void logout(String token) {
        Token verification = tokenService.verification(token);
        if ( verification == null )
            throw new TokenException(TOKEN_INVALID, "令牌无效.");
        tokenService.deleteToken(verification);
    }

}
